<?php
namespace app;

use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\exception\Handle;
use think\exception\HttpException;
use think\exception\HttpResponseException;
use think\exception\ValidateException;
use think\exception\RouteNotFoundException;
use think\response\Json;
use Throwable;
// use EasyWeChat\Kernel\Exceptions\Exception as WechatException;
/**
 * 应用异常处理类
 */
class ExceptionHandle extends Handle
{
    /**
     * 不需要记录信息（日志）的异常类列表
     * @var array
     */
    protected $ignoreReport = [
        HttpException::class,
        HttpResponseException::class,
        ModelNotFoundException::class,
        DataNotFoundException::class,
        ValidateException::class,
        RouteNotFoundException::class
    ];

    /**
     * 记录异常信息（包括日志或者其它方式记录）
     *
     * @access public
     * @param  Throwable $exception
     * @return void
     */
    public function report(Throwable $exception): void
    {
        // 使用内置的方式记录异常日志
        parent::report($exception);
    }


    /**
     * Render an exception into an HTTP response.
     *
     * @access public
     * @param \think\Request   $request
     * @param Throwable $e
     * @return Json
     */
    public function render($request, Throwable $e): Json
    {
        // 路由错误
        if ($e instanceof RouteNotFoundException) {
            $result = ['code' => 404, 'msg' => '当前路由不存在'];
        }
        // 数据不存在
        elseif ($e instanceof ModelNotFoundException || $e instanceof DataNotFoundException) {
            $result = ['code' => 404, 'msg' => '当前查询数据不存在'];
        }
        /*
        // 微信sdk相关错误
        elseif ($e instanceof WechatException) {
            $result = ['code' => $e->getCode() + 222, 'msg' => strchr($e->getMessage(), 'error: ')];
        }
        */
        // 参数验证错误
        elseif ($e instanceof ValidateException) {
            $result = ['code' => 422, 'msg' => $e->getError()];
        }
        // 请求异常
        elseif ($e instanceof HttpException) {
            $result = ['code' => $e->getStatusCode(),  'msg' => '11111'];
        } else {
            $result = ['code' => $e->getCode(),  'msg' => $e->getMessage()];
        }
        // 添加自定义异常处理机制
        return json($result);
        // return parent::render($request, $e);
    }
}
